import React, { memo } from 'react';
import { TreeSelect, Tree, Spin } from 'antd';
import { defaultFormatResult, useRequest } from '@/hooks';
import { fetchOrgEmployee } from '../service';

const { TreeNode } = Tree;

const renderTreeNode = data =>
    data.map(item => {
        let orgEmployeeList;
        if (item.orgEmployeeList && item.orgEmployeeList.length) {
            orgEmployeeList = item.orgEmployeeList.map(employee => <TreeNode
                key={employee.employeeCode}
                value={employee.employeeCode}
                title={employee.employeeName}
                />)
        }
        // if (!item.children && !orgEmployeeList) return undefined;
        if (item.children && item.children.length) {
            return (
                <TreeNode
                    selectable={false}
                    key={item.organizationCode}
                    value={item.organizationCode}
                    title={item.organizationName}
                >
                    {renderTreeNode(item.children)}
                    { orgEmployeeList }
                </TreeNode>
            );
        }
        return (
            <TreeNode
                selectable={false}
                key={item.organizationCode}
                value={item.organizationCode}
                title={item.organizationName}
            >
                { orgEmployeeList }
            </TreeNode>
        );
    }).filter(item => item);
const OrgEmployeeTree = memo(({ organizationCode, style, ...rest }) => {
    const { data: treeData = [], loading } = useRequest(() => fetchOrgEmployee(organizationCode), {
        initialData: [],
        refreshDeps: [organizationCode],
        ...defaultFormatResult
    });
    return <Spin spinning={loading}>
        <TreeSelect
            style={{ width: 170, ...style }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择或输入"
            treeNodeFilterProp="title"
            showSearch
            {...rest}
        >
            {renderTreeNode(treeData)}
        </TreeSelect>
    </Spin>
});

export default OrgEmployeeTree;
